package com.example.db2dm.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DatabaseUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(DatabaseUtil.class);
    
    /**
     * 建立数据库连接
     * @param url 数据库URL
     * @param username 用户名
     * @param password 密码
     * @return 数据库连接
     * @throws SQLException SQL异常
     */
    public static Connection getConnection(String url, String username, String password) throws SQLException {
        try {
            // 设置连接属性，确保使用UTF-8字符集
            Properties props = new Properties();
            props.setProperty("user", username);
            props.setProperty("password", password);
            props.setProperty("charset", "UTF-8");
            
            return DriverManager.getConnection(url, props);
        } catch (SQLException e) {
            logger.error("数据库连接失败: URL={}, Username={}", url, username, e);
            throw e;
        }
    }
    
    /**
     * 关闭数据库连接
     * @param connection 数据库连接
     */
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                logger.warn("关闭数据库连接时发生错误", e);
            }
        }
    }
}